import {adjustPath, iMicroApp, pathJoin} from "@peryl/micro-web";
import {Crm} from "./router/Crm";
import {Erp} from "./router/Erp";
import {CrmHome} from "./router/CrmHome";
import {ErpHome} from "./router/ErpHome";
import {RouterLogin} from "./router/RouterLogin";
import {RouterPrivate} from "./router/RouterPrivate";
import {RouterPublic} from "./router/RouterPublic";
import {RouterPage} from "./router/RouterPage";
import * as PlainDesign from 'plain-design';
import {i18n} from 'plain-design';
import * as PerylReactCompose from '@peryl/react-compose';
import React from 'react';
import ReactDOM from 'react-dom';
import {env} from "./env";

export const applyAppConfig = (microApp: iMicroApp) => {

  /*假设所有子应用部署的服务器都有跨域限制，这里是因为码云部署的单页面有跨域限制*/
  const hasCorsLimit = true;
  /*当前是否为本地调试主应用*/
  const isDevelopment = process.env.NODE_ENV === 'development';
  /*判断当前访问子应用是否需要通过代理服务*/
  const needProxy = hasCorsLimit && isDevelopment;
  /*子应用部署的域名*/
  // const subAppOrigin = needProxy ? 'http://localhost:3888' : `${location.protocol}//peryl.gitee.io/`;
  const subAppOrigin = needProxy ? 'http://localhost:3888' : env.assetsPrefix;
  // const subAppOrigin = env.assetsPrefix;

  /*子应用全部连接本地地址*/
  // const localDebug = true;
  const localDebug = false;
  /*---------------------------------------子应用定义-------------------------------------------*/

  /*base内置应用*/
  microApp.registry({
    id: 'react-base',
    index: () => microApp.createLocalIndexConfig({
      getPageComponent: async ({ page, microConfig }) => {
        let path = pathJoin('/' + page.path);
        const microId = pathJoin('/' + microConfig.id + '/');
        path = path.slice(microId.length);
        if (path.indexOf('-page') > -1) {path = path.slice(0, '-page'.length * -1);}
        path = pathJoin('/' + path);

        try {
          /*尝试加载多语言文件*/
          await import('src/pages' + path + '-page.locale').then(i => {i18n.setLangs(i.default);});
        } catch (e) {
          /*do nothing*/
        }
        return import('src/pages' + path + '-page').then(i => i.default);
      }
    })
  });

  /*---------------------------------------联调远程子应用的话，本地调试时通过3888代理解决跨域问题，打包时直接使用远程同域地址；如果部署的服务器开启放开跨域限制，则可以一直使用远程子应用地址-------------------------------------------*/

  /*react 子应用*/
  microApp.registry({
    id: 'react-sub-vuecli',
    index: () => pathJoin(subAppOrigin, '/micro-web-react-sub-vuecli/'),
  });

  /*vue子应用*/
  microApp.registry({
    id: 'vue-sub-vuecli',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-vuecli/'),
  });

  microApp.registry({
    id: 'vue-sub-vuecli-router',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-vuecli-router/'),
  });

  microApp.registry({
    id: 'react-sub-cra-router',
    index: () => pathJoin(subAppOrigin, '/micro-web-react-sub-cra-router/'),
  });

  microApp.registry({
    id: 'vue-sub-vite-router',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-vite-router/'),
  });

  microApp.registry({
    id: 'react-sub-vite-router',
    index: () => pathJoin(subAppOrigin, '/micro-web-react-sub-vite-router/'),
  });

  microApp.registry({
    id: 'vue-sub-vite',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-vite/'),
  });

  microApp.registry({
    id: 'react-sub-vite',
    index: () => pathJoin(subAppOrigin, '/micro-web-react-sub-vite/'),
  });

  microApp.registry({
    id: 'vue-sub-iview-admin',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-iview-admin/'),
  });

  microApp.registry({
    id: 'react-sub-arco-admin',
    index: () => pathJoin(subAppOrigin, '/micro-web-react-sub-arco-admin/'),
  });

  microApp.registry({
    id: 'vue-sub-element-admin',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-element-admin/'),
  });

  microApp.registry({
    id: 'vue-sub-elementplus-admin',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-elementplus-admin/'),
  });

  microApp.registry({
    id: 'vue-sub-element-plus',
    index: () => pathJoin(subAppOrigin, '/micro-web-vue-sub-element-plus/'),
  });

  microApp.registry({
    id: 'react-sub-umi4-antdpro',
    publicPath: 'micro-web-react-sub-umi4-antdpro',
    index: (tokenInfo) => pathJoin(subAppOrigin, `/micro-web-react-sub-umi4-antdpro/micro?layout=N&token=${tokenInfo.token}`),
    iframe: {
      formatPath: ({ purePagePath, baseFullPagePath, subFullPagePath, tokenInfo }) => {
        const adjustPathHandler = (url: URL) => {
          url.searchParams.set('token', tokenInfo.token || 'yy_yyyy');
          url.searchParams.set('layout', 'N');
        };
        return {
          purePagePath: adjustPath(purePagePath, adjustPathHandler),
          subFullPagePath: adjustPath(subFullPagePath, adjustPathHandler),
          baseFullPagePath: adjustPath(baseFullPagePath, adjustPathHandler),
          tokenInfo
        };
      },
    },
  });

  microApp.registry({
    id: 'react-sub-cra-router-antd',
    index: () => pathJoin(subAppOrigin, '/micro-web-react-sub-cra-router-antd/'),
  });

  microApp.registry({
    id: 'react-sub-vuecli-formily',
    index: () => pathJoin(subAppOrigin, '/micro-web-react-sub-vuecli-formily/'),
  });

  /*---------------------------------------联调本地子应用-------------------------------------------*/

  if (localDebug) {
    /*react 子应用*/
    microApp.registry({
      id: 'react-sub-vuecli',
      index: () => 'http://localhost:4002/micro-web-react-sub-vuecli/'
    });

    /*vue子应用*/
    microApp.registry({
      id: 'vue-sub-vuecli',
      index: () => 'http://localhost:4003/micro-web-vue-sub-vuecli/'
    });

    microApp.registry({
      id: 'vue-sub-vuecli-router',
      index: () => 'http://localhost:4004/micro-web-vue-sub-vuecli-router/'
    });

    microApp.registry({
      id: 'react-sub-cra-router',
      index: () => 'http://localhost:4005/micro-web-react-sub-cra-router/'
    });

    microApp.registry({
      id: 'vue-sub-vite-router',
      index: () => 'http://localhost:4006/micro-web-vue-sub-vite-router/',
    });

    microApp.registry({
      id: 'react-sub-vite-router',
      index: () => 'http://localhost:4007/micro-web-react-sub-vite-router/',
    });

    microApp.registry({
      id: 'vue-sub-vite',
      index: () => 'http://localhost:4008/micro-web-vue-sub-vite/',
    });

    microApp.registry({
      id: 'react-sub-vite',
      index: () => 'http://localhost:4009/micro-web-react-sub-vite/',
    });

    microApp.registry({
      id: 'vue-sub-iview-admin',
      index: () => 'http://localhost:4010/micro-web-vue-sub-iview-admin/',
    });

    microApp.registry({
      id: 'react-sub-arco-admin',
      index: () => 'http://localhost:4011/micro-web-react-sub-arco-admin/',
    });

    microApp.registry({
      id: 'vue-sub-element-admin',
      index: () => 'http://localhost:4012/micro-web-vue-sub-element-admin/',
    });

    microApp.registry({
      id: 'vue-sub-elementplus-admin',
      index: () => 'http://localhost:4013/micro-web-vue-sub-elementplus-admin/',
    });

    microApp.registry({
      id: 'vue-sub-element-plus',
      index: () => 'http://localhost:4014/micro-web-vue-sub-element-plus/',
    });

    microApp.registry({
      id: 'react-sub-umi4-antdpro',
      publicPath: 'micro-web-react-sub-umi4-antdpro',
      index: (tokenInfo) => `http://localhost:4015/micro-web-react-sub-umi4-antdpro/micro?layout=N&token=${tokenInfo.token}`,
      iframe: {
        formatPath: ({ purePagePath, baseFullPagePath, subFullPagePath, tokenInfo }) => {
          const adjustPathHandler = (url: URL) => {
            url.searchParams.set('token', tokenInfo.token || 'yy_yyyy');
            url.searchParams.set('layout', 'N');
          };
          return {
            purePagePath: adjustPath(purePagePath, adjustPathHandler),
            subFullPagePath: adjustPath(subFullPagePath, adjustPathHandler),
            baseFullPagePath: adjustPath(baseFullPagePath, adjustPathHandler),
            tokenInfo
          };
        },
      },
    });

    microApp.registry({
      id: 'react-sub-cra-router-antd',
      index: () => 'http://localhost:4016/micro-web-react-sub-cra-router-antd/',
    });

    microApp.registry({
      id: 'react-sub-vuecli-formily',
      index: () => 'http://localhost:40020/micro-web-react-sub-vuecli-formily/',
    });
  }

  /*---------------------------------------公共资源定义-------------------------------------------*/

  // microApp.resource.registry({ name: 'React', loader: { js: 'libs/react.production.min.js' }, version: '18.0.1' });
  // microApp.resource.registry({ name: 'ReactDOM', loader: { js: 'libs/react-dom.production.min.js' }, version: '18.0.1', dependencies: ['React'] });
  microApp.resource.registry({ name: 'React', loader: async () => React, version: '18.0.1' });
  microApp.resource.registry({ name: 'react', globalName: 'React', loader: async () => React, version: '18.0.1' });
  microApp.resource.registry({ name: 'jsx-runtime', globalName: 'React', loader: { js: 'libs/react-jsx-runtime.production.min.js' }, version: '17.0.2', dependencies: ['react'] });
  microApp.resource.registry({ name: 'ReactDOM', loader: async () => ReactDOM, version: '18.0.1' });
  microApp.resource.registry({ name: 'react-dom', globalName: 'ReactDOM', loader: async () => ReactDOM, version: '18.0.1' });
  microApp.resource.registry({ name: 'PerylReactCompose', loader: async () => PerylReactCompose, version: '0.0.215', dependencies: ['jsx-runtime'] });
  microApp.resource.registry({ name: '@peryl/react-compose', globalName: 'PerylReactCompose', loader: async () => PerylReactCompose, version: '0.0.215', dependencies: ['jsx-runtime'] });
  microApp.resource.registry({ name: 'PlainDesign', loader: async () => PlainDesign, version: '1.0.0-beta.37', dependencies: ['@peryl/react-compose'] });
  microApp.resource.registry({ name: 'plain-design', globalName: 'PlainDesign', loader: async () => PlainDesign, version: '1.0.0-beta.37', dependencies: ['@peryl/react-compose'] });

  microApp.resource.registry({ name: 'Vue', loader: { js: 'libs/vue.global.min.js' }, version: '3.3.4' });
  microApp.resource.registry({ name: 'PlainUiComposition', loader: { js: 'libs/plain-ui-composition.umd.min.js' }, version: '0.0.101', dependencies: ['Vue'] });
  microApp.resource.registry({ name: 'PlainUi', loader: { js: 'libs/plain-ui.min.js', css: 'libs/plain-ui.min.css' }, version: '1.0.12', dependencies: ['Vue', 'PlainUiComposition', 'Axios'] });

  microApp.resource.registry({ name: 'Axios', globalName: 'axios', loader: { js: 'libs/axios.min.js' }, version: '1.5.0' });
  microApp.resource.registry({ name: 'echarts', loader: { js: 'libs/echarts.min.js' }, version: '1.5.0' });
  microApp.resource.registry({ name: 'pinyin', loader: { js: 'libs/pinyin.min.js' }, version: '1.5.0' });
  microApp.resource.registry({ name: 'JSZip', loader: { js: 'libs/jszip.js' }, version: '3.10.1' });
  microApp.resource.registry({ name: 'PptxGenJS', loader: { js: 'libs/pptxgen.min.js' }, version: '3.12.0' });
  microApp.resource.registry({ name: 'babel', globalName: 'Babel', loader: { js: 'libs/babel.min.js' }, version: '7.15.8' });
  microApp.resource.registry({ name: 'jsx-model', globalName: 'JSXModel', loader: { js: 'libs/babel-plugin-react-model.js' }, version: '0.0.150', dependencies: ['babel'] });
  /*---------------------------------------路由定义-------------------------------------------*/

  microApp.route.defineLayoutRoute({ default: true, path: 'crm', render: () => <Crm/> });         // 默认路由为crm
  microApp.route.defineLayoutRoute({ path: 'home', render: () => <CrmHome/> });                   // crm home路由
  microApp.route.defineLayoutRoute({ path: 'erp', render: () => <Erp/> });                        // 系统erp
  microApp.route.defineLayoutRoute({ path: 'erphome', render: () => <ErpHome/> });                // erp home路由
  microApp.route.defineLayoutRoute({ path: 'login', render: () => <RouterLogin/> });              // 登录路由
  microApp.route.defineLayoutRoute({ path: 'private', render: () => <RouterPrivate/> });          // 私有页面路由
  microApp.route.defineLayoutRoute({ path: 'public', render: () => <RouterPublic/> });            // 公开页面路由
  microApp.route.defineLayoutRoute({ path: 'page', render: () => <RouterPage/> });                // 内置页面路由

  microApp.route.definePageRoute({ route: '/public/403', path: 'react-base/core/403-page', });
  microApp.route.definePageRoute({ route: '/public/404', path: 'react-base/core/404-page', });
  microApp.route.definePageRoute({ route: '/public/500', path: 'react-base/core/500-page', });

  microApp.route.definePageRoute({ route: '/private/order/:privateCode', path: 'react-base/demo/demo-private-layout-page', });
  microApp.route.definePageRoute({ route: '/public/order/:publicCode', path: 'react-base/demo/demo-public-layout-page', });
  microApp.route.definePageRoute({ route: '/page/order/:pageCode', path: 'react-base/demo/demo-page-layout-page', });
  microApp.route.definePageRoute({ route: '/home/menu/:menuCode', path: 'react-base/core/home-menu-page', title: 'TestHomeRouteMenu' });/*通过menuCode打开指定的菜单*/
  microApp.route.definePageRoute({ route: '/home/path/:pagePath', path: 'react-base/core/home-path-page', title: 'TestHomeRoutePath' });/*通过pagePath打开指定页面*/
};
